import * as service from '../services';
import {PAGE_NUM, TRANSACTIONS_PAGE_SIZE} from "@/constants";

export default {
  namespace: 'transactions',
  state: {
    list: [],
    total: null,
    page: null,
  },
  reducers: {
    save(state, { payload: { list, total, page }}) {
      return { ...state, list, total, page  };
    }
  },
  effects: {
    *fetch({ payload: { hashOrHeight, page = PAGE_NUM, size = TRANSACTIONS_PAGE_SIZE }}, {call, put}) {
      const response = yield call(service.getBlockTransactions, hashOrHeight, page, size);
      const result = response.data;
      yield put({
        type: 'save',
        payload: {
          list: result ? result.data : [],
          total: result ? result.total: null,
          page: result ? result.pageNum: null,
        }
      });
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname.startsWith('/block/')) {
          let paths = location.pathname.split('/');
          let hashOrHeight = paths.pop();
          dispatch({ type: 'fetch', payload: { hashOrHeight } });
        }
      });
    },
  },
}
